<?php

namespace api\modules\v1\models;

use Yii;
use common\models\User;
use common\models\UserToken;
use yii\base\Model;
use yii\validators\EmailValidator;
use yii\validators\NumberValidator;

/**
 * This is the model class for table "{{%member}}".
 *
 * @property integer $member_id
 * @property string $member_name
 * @property integer $inviter_id 
 */
class LoginForm extends Model
{
    public $username;
    public $password;
    public $client;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password', 'client'], 'required'],
            [['username'], 'string', 'max' => 50],
            [['password'], 'string', 'max' => 32],
            [['client'], 'string', 'max' => 10],
        ];
    }
    
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'username' => Yii::t('app', '会员名称'),
            'password' => Yii::t('app', '会员密码'),
            'client' => Yii::t('app', '客户端类型'),
        ];
    }
  
    /**
     * @inheritdoc
     */
    public function getToken($username, $password, $client)
    {
        $model = new User();
        $validator = new EmailValidator();
        if($validator->validate($username)){
            $user = $model->findByEmail($username);
        }elseif(strlen($username)==11){
            $validator = new NumberValidator();
            if($validator->validate($username)){
                $operators = array(
                    134, 135, 136, 137, 138, 139, 147, 150, 151, 152, 157, 158, 159, 182, 187, 188, // 中国移动
                    130, 131, 132, 145, 155, 156, 185, 186, 145, // 中国联通
                    133 , 153 , 180 , 181 , 189, // 中国电信
                );
                if(in_array(substr($username,0,3),$operators)){
                    $user = $model->findByMobile($username);
                }
            }
        }else{
            $user = $model->findByUsername($username);
        }
        if (!empty($user)) {
            if ($user->validatePassword($password)) {
                
//                 $user->member_old_login_time = $user->member_login_time;
//                 $user->member_login_time = strval(time());
//                 $user->member_old_login_ip = $user->member_login_ip;
//                 $user->member_login_ip = $_SERVER['REMOTE_ADDR'];
//                 $user->save();
                return $this->createToken($user->id, $user->username, $client);
            } else {
                $model->addError('password', '会员密码错误');
            }
        } else {
            $model->addError('username', '登陆失败');
        }
        return $model;
    }
    /**
     * 创建 Token
     *
     * @param string $member_id 用户ID
     * @param string $member_name 用户名
     * @param string $client 设备类型 android/wap/ios
     * @return array
     */
    public function createToken($id, $username, $client)
    {
//         $mb_user_token = new MbUserToken();
        // 重新登录后以前的令牌失效
//         $mb_user_token->deleteAll([
//             'member_id' => $member_id,
//             'client_type' => $client
//         ]);
        // 生成新的token
        $user_token = UserToken::findOne([
            'user_id' => $id,
            'username' => $username,
            'client_type' => $client
        ]);
        if(empty($user_token)){
            $user_token = new UserToken();
        }
        $time = time();
        $user_token->user_id = $id;
        $user_token->client_type = $client;
        $user_token->access_token = yii::$app->security->generateRandomString();
        $user_token->access_expire = time();
        $user_token->username = $username;
        $user_token->login_time = $time;
        $user_token->login_ip = yii::$app->request->userIP;
        $user_token->save();
        return $user_token;
    }
}
